<?php
namespace app\admin\controller;

use think\exception\ValidateException;
use think\facade\Request;
use think\facade\Filesystem;

class Upload
{
    public static function getPathsInfo($name = 'img',$dir='linshi/upload',$rule='data')
    {
        try{
            $file = Request::file();
            validate([$name => 'filesize:102400|fileExt:jpg,png'])->check($file);
            $paths = [];
            if (is_array($file[$name])){
                foreach ($file[$name] as $img){
                    $path = Filesystem::putFile($dir,$img,$rule);
                    $paths[] = str_replace('\\','/',$path);
                }
                $paths = implode(',',$paths);
            }else{
                $path = Filesystem::putFile($dir,$file[$name],$rule);
                $paths = str_replace('\\','/',$path);
            }
        } catch (ValidateException $e){
            return[false,$e->getMessage()];
        } catch (\Exception $e){
            $paths = '';
         }
        return [true,$paths];
    }
    //ajax上传
    public function ajaxUpload()
    {
        list($strtic,$list) = self::getPathsInfo('img');
        return json($list);
    }
    //单图上传
    public static function imgUpload($image)
    {
        //有图上传时
        $linshi_image = $image;
        //获取文件格式
        $s = explode('.',$linshi_image);
        //正式路径
        $path_date = date('Y/m/d/');
        $path_dir = $path_date.md5(microtime(true).rand(100000,999999)).'.'.end($s);
//        $edit['images'] = $path_dir;
        return [$path_dir,$path_date];
    }
    //多图上传
    public static function imgsUpload($post)
    {
        $post['imgs'] = [];
        $new_img = [];
        if (isset($post['new_img'])){
            foreach ($post['new_img'] as $v){
                //获取文件格式
                $s = explode('.',$v);
                //正式路径
                $path_date = date('Y/m/d/');
                $path_dir = $path_date.md5(microtime(true).rand(100000,999999)).'.'.end($s);
                $post['imgs'][] = $path_dir;
                //移动路径用的data
                $new_img[] = [
                    'new'=>$path_dir,
                    'old'=>$v
                ];
            }
        }
        if (isset($post['old_img'])){
            $post['imgs'] = array_merge($post['old_img'],$post['imgs']);
        }
        $post['imgs'] = implode(',',$post['imgs']);
        return [$post,$new_img];
    }


}